package org.mch.comm.entity;

import java.beans.PropertyDescriptor;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.BeanUtilsBean;
import org.mch.comm.itf.IBaseEO;

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonInclude.Include;

@JsonInclude(Include.NON_NULL)
public class MBaseEO extends HashMap<String, Object> implements IBaseEO {
	private static final long serialVersionUID = 6133264624733394185L;

	// JSON解析忽略该字段
	@JsonIgnore
	private transient Map<String, Class<?>> filedClasss = new HashMap<String, Class<?>>();

	// JSON解析忽略该字段
	@JsonIgnore
	private transient List<String> fieldNames = new ArrayList<String>();
	public static final Set<String> PcFieldSet = new HashSet<String>();
	static {
		PcFieldSet.add("fieldNames");
		PcFieldSet.add("filedClasss");
		PcFieldSet.add("filedValue");
		PcFieldSet.add("class");
	}

	public MBaseEO() {
		super();
		initEO();
	}

	private void initEO() {
		/*
		 * 初始化时，获得当前实体所有属性，并存储；
		 */
		PropertyDescriptor[] pros = BeanUtilsBean.getInstance().getPropertyUtils().getPropertyDescriptors(this);
		for (PropertyDescriptor prod : pros) {
			if (PcFieldSet.contains(prod.getName())) {
				continue;
			}
			fieldNames.add(prod.getName());
			filedClasss.put(prod.getName(), prod.getPropertyType());
		}
	}

	@Override
	public String toString() {
		StringBuilder sb = new StringBuilder();
		for (String fieldName : fieldNames) {
			sb.append(fieldName);
			sb.append("=");
			try {
				sb.append(BeanUtils.getProperty(this, fieldName));
			} catch (Exception e) {
				e.printStackTrace();
			}
			sb.append("\n");
		}
		return sb.toString();
	}

	public String[] getFieldNames() {
		return fieldNames.toArray(new String[0]);

	}

	public Class<?> getFieldClass(String fieldName) {
		return filedClasss.get(fieldName);
	}

	@SuppressWarnings("unchecked")
	@JsonIgnore
	@Override
	public <E> E get(String fieldname) {
		try {
			return (E) BeanUtils.getProperty(this, fieldname);
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	@SuppressWarnings("unchecked")
	@JsonIgnore
	@Override
	public <E> E get(String fieldname, Class<E> type) {
		try {
			return (E) BeanUtils.getProperty(this, fieldname);
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	@Override
	public MBaseEO set(String fieldName, Object value) {
		try {
			BeanUtils.setProperty(this, fieldName, value);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return this;
	}

	@Override
	public Object put(String key, Object value) {
		return super.put(key, value);
	}
}
